import { getFromStorage, saveToStorage } from "../storage.js";

const RATES_KEY = "fx_rates";
const RATES_TTL_MS = 1000 * 60 * 60; // 1 hour

export async function fetchRates() {
  const res = await fetch("https://api.frankfurter.app/latest");
  if (!res.ok) throw new Error("Failed to fetch rates");
  const data = await res.json();
  const payload = {
    base: data.base,
    date: data.date,
    rates: data.rates,
    ts: Date.now(),
  };
  await saveToStorage(RATES_KEY, payload);
  return payload;
}

export async function getRates() {
  const cached = await getFromStorage(RATES_KEY);
  if (cached && Date.now() - (cached.ts || 0) < RATES_TTL_MS) return cached;
  return fetchRates();
}

export async function refreshRatesIfStale(force = false) {
  const cached = await getFromStorage(RATES_KEY);
  if (force || !cached || Date.now() - (cached.ts || 0) >= RATES_TTL_MS) {
    try {
      await fetchRates();
    } catch (_e) {}
  }
}
